<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">

      <el-row v-show="showSearch" class="query_el_row-wrapper">
        <el-col :span="17">
          <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
            <el-form-item label="设备ID" prop="devId">
              <el-input placeholder="请输入设备ID" v-model="state.queryForm.devId"/>
            </el-form-item>
            <el-form-item label="消息类型" prop="messageType">
              <el-select v-model="state.queryForm.messageType" placeholder="请选择消息类型">
                <el-option :key="index" :label="item" :value="item"
                           v-for="(item, index) in thisPageState.uniqueMessageTypes"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="消息状态" prop="messageStatement">
              <el-select v-model="state.queryForm.messageStatement" placeholder="请选择消息状态">
                <el-option :key="index" :label="item" :value="item"
                           v-for="(item, index) in thisPageState.uniqueMessageStatements"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="7">
          <div class="query_button_wrap">
            <el-button icon="search" type="primary" @click="getDataList">
              查询
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </div>
        </el-col>
      </el-row>

      <el-row class="add_el_row_wrapper">
        <el-col :span="15" class="add_el_button_el_col">
          <el-button icon="folder-add" type="primary" class="ml10" @click="formDialogRef.openDialog()"
                     v-auth="'iot_iotDeviceMessage_add'">
            添加消息
          </el-button>
          <el-button plain :disabled="multiple" icon="Delete" type="primary"
                     v-auth="'iot_iotDeviceMessage_del'" @click="handleDelete(selectObjs)">
            删除消息
          </el-button>
        </el-col>

        <el-col :span="9" class="right_tool_el_col">
          <div style="margin-right: 10px"></div>
          <right-toolbar v-model:showSearch="showSearch" :export="'farm_farmGreenhouse_export'"
                         @exportExcel="exportExcel" class="ml10 mr20"
                         @queryTable="getDataList"></right-toolbar>
        </el-col>
      </el-row>

      <el-table :data="state.dataList" v-loading="state.loading"
                :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
                @selection-change="selectionChangHandle"
                @sort-change="sortChangeHandle">
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column type="index" label="#" width="40" />
        <el-table-column prop="devId" label="设备ID"  show-overflow-tooltip/>
        <el-table-column label="预警图片" width="130">
          <template #default="scope">
            <div style="width: 100%;cursor: pointer" @click="previewImg(scope)">
              <el-image :src="thisPageState.imgBaseUrl + getImageUrl(scope.row)" :fit="'cover'"
                        style="width: 100px;height: 100px">
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="devDataId" label="采集数据外键ID"  show-overflow-tooltip/>
        <el-table-column prop="messageType" label="消息类型 "  show-overflow-tooltip/>
        <el-table-column prop="messageDescribe" label="消息描述"  show-overflow-tooltip/>
        <el-table-column prop="messageSpecialInfo" label="消息特定信息"  show-overflow-tooltip/>
        <el-table-column prop="messageStatement" label="消息状态"  show-overflow-tooltip/>
        <el-table-column prop="createBy" label="创建人"  show-overflow-tooltip/>
        <el-table-column prop="updateBy" label="修改人"  show-overflow-tooltip/>
        <el-table-column prop="createTime" label="上传时间"  show-overflow-tooltip/>
        <el-table-column prop="updateTime" label="更新时间"  show-overflow-tooltip/>
        <el-table-column prop="delFlag" label="删除标志"  show-overflow-tooltip/>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button icon="edit-pen" text type="primary" v-auth="'iot_iotDeviceMessage_edit'"
                       @click="formDialogRef.openDialog(scope.row.id)">编辑</el-button>
            <el-button icon="delete" text type="primary" v-auth="'iot_iotDeviceMessage_del'" @click="handleDelete([scope.row.id])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-image-viewer v-if="thisPageState.showImg"
                       :url-list="thisPageState.imgList"
                       :initial-index="thisPageState.imgViewIndex"
                       @close="thisPageState.showImg = false">
      </el-image-viewer>

      <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
    </div>


    <!-- 编辑、新增  -->
    <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />

  </div>
</template>

<script setup lang="ts" name="systemIotDeviceMessage">
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs } from "/@/api/iot/iotDeviceMessage";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { useDict } from '/@/hooks/dict';

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
// 定义查询字典

// 定义变量内容
const formDialogRef = ref()
// 搜索变量
const queryRef = ref()
const showSearch = ref(true)
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)

const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: fetchList,
  handleDataListcallBack: sortData // 添加排序回调
})

//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state)

// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields()
  // 清空多选
  selectObjs.value = []
  getDataList()
}

// 导出excel
const exportExcel = () => {
  downBlobFile('/iot/iotDeviceMessage/export',Object.assign(state.queryForm, { ids: selectObjs }), 'iotDeviceMessage.xlsx')
}

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({ id }) => id);
  multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};

/**
 * 去除模板中直接使用的statu自定义一个自己需要使用的 页面state
 */
const thisPageState = reactive({
  deviceMessageList: [],//所有设备消息
  imgBaseUrl:"/api", //后端地址 预览图片
  showImg:false,
  imgList:[],
  imgViewIndex:0,
  uniqueMessageTypes: [], // 去重后的消息类型
  uniqueMessageStatements: [] ,// 去重后的消息状态
  imgBaseUrl: "/api",
  showImg: false,
})

/**
 * 获取后端地址
 */
thisPageState.imgBaseUrl = import.meta.env.VITE_API_URL

/**
 * 获取所有设备分类信息
 *
 */

function getDeviceMessageList() {
  fetchList().then(res => {
    console.log(res)
    thisPageState.deviceMessageList = res.data.records;
    // 去重处理
    thisPageState.uniqueMessageTypes = [...new Set(res.data.records.map(item => item.messageType))];
    thisPageState.uniqueMessageStatements = [...new Set(res.data.records.map(item => item.messageStatement))];
  })
}
function sortData() {
  state.dataList = state.dataList.sort((a, b) => {
    return new Date(b.createTime) - new Date(a.createTime); // 倒序排列
  });
}

function getImageUrl(item) {
  const match = item.messageSpecialInfo.match(/url=([^}]+)/);
  return match ? match[1] : '';
}
const previewImg = (scope) => {
  thisPageState.showImg = true;
  thisPageState.imgViewIndex = scope.$index;
};
getDeviceMessageList()

</script>